import React, { ChangeEvent, FC, useState } from "react"
import styles from "./EditHeader.module.scss"
import { EditOutlined, LeftOutlined, LoadingOutlined } from "@ant-design/icons"
import { Button, Typography, Space, Input, message } from "antd"
import { useNavigate, useParams } from "react-router-dom"
import EditToolbar from "./EditToolbar"
import useGetPageInfo from "../../../../hooks/useGetPageInfo"
import { useDispatch } from "react-redux"
import { changePageTitle } from "../../../../store/pageInfoReducer"
import useGetComponentInfo from "../../../../hooks/useGetComponentInfo"
import { useDebounceEffect, useKeyPress, useRequest } from "ahooks"
import { updateQuestionService } from "../../../../services/question"

const { Title } = Typography

// 显示和修改标题
const TitleElem: FC = () => {
    const { title } = useGetPageInfo()
    const dispatch = useDispatch()

    const [editState, SetEditState] = useState(false)

    // 修改标题
    function handleChange(event: ChangeEvent<HTMLInputElement>) {
        // 获取新的title
        const newTitle = event.target.value.trim()
        if (!newTitle) return
        dispatch(changePageTitle(newTitle))
    }

    if (editState) {
        return <Input value={title} autoFocus onChange={e => handleChange(e)} onPressEnter={() => SetEditState(false)} onBlur={() => SetEditState(false)} />
    }
    return (
        <Space>
            <Title>{title} </Title>
            <Button icon={<EditOutlined />} type="text" onClick={() => SetEditState(true)} />
        </Space>
    )
}

// 保存按钮
const SaveButton: FC = () => {
    // 保存pageInfo和componentList的信息

    // 获取id（id在url中）
    const { id } = useParams()
    const { componentList = [] } = useGetComponentInfo() // 其它值（selectedId,selectedComponent,copiedComponent）是辅助编辑的，不需要保存
    const pageInfo = useGetPageInfo() // pageInfo所有的值都需要保存

    // 快捷键保存
    useKeyPress(["ctrl.s", "meta.s"], (event: KeyboardEvent) => {
        // 阻止默认行为
        event.preventDefault()
        if (!loading) save()
    })

    // 自动保存（当改变时才进行保存，并不是定期保存）
    // useDebounceEffect就有useEffect的效果，还可以实现防抖效果
    useDebounceEffect(
        () => {
            save()
        },
        [componentList, pageInfo],
        { wait: 10000 }
    )

    // 将run方法重命名为save
    const { loading, run: save } = useRequest(
        async () => {
            if (!id) return
            await updateQuestionService(id, { ...pageInfo, componentList })
        },
        {
            manual: true,
            onSuccess() {
                message.success("保存成功")
            }
        }
    )

    return (
        <Button onClick={save} disabled={loading} icon={loading ? <LoadingOutlined /> : null}>
            保存
        </Button>
    )
}

const PublishButton: FC = () => {
    // 修改isPublished属性

    // 获取id（id在url中）
    const { id } = useParams()

    const nav = useNavigate()

    const { componentList = [] } = useGetComponentInfo() // 其它值（selectedId,selectedComponent,copiedComponent）是辅助编辑的，不需要保存
    const pageInfo = useGetPageInfo() // pageInfo所有的值都需要保存

    // 快捷键保存
    useKeyPress(["ctrl.s", "meta.s"], (event: KeyboardEvent) => {
        // 阻止默认行为
        event.preventDefault()
        if (!loading) pub()
    })

    // 将run方法重命名为save
    const { loading, run: pub } = useRequest(
        async () => {
            if (!id) return
            // isPublished: true标志着问卷被发布（也需要修改信息，只不过多了一个isPublished）
            await updateQuestionService(id, { ...pageInfo, componentList, isPublished: true })
        },
        {
            manual: true,
            onSuccess() {
                message.success("发布成功")
                // 跳转到统计页面
                nav("/question/stat/" + id)
            }
        }
    )
    return (
        <Button type="primary" onClick={pub} disabled={loading}>
            发布
        </Button>
    )
}

// 编辑器头部
const EditHeader: FC = () => {
    const nav = useNavigate()

    return (
        <div className={styles["header-wrapper"]}>
            <div className={styles.header}>
                <div className={styles.left}>
                    <Space>
                        <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
                            返回
                        </Button>
                        <TitleElem />
                    </Space>
                </div>
                <div className={styles.main}>
                    <EditToolbar />
                </div>
                <div className={styles.right}>
                    <Space>
                        <SaveButton />
                        <PublishButton />
                    </Space>
                </div>
            </div>
        </div>
    )
}

export default EditHeader
